﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using ZRT.RHPX.Core.Mvc.Controllers;
using ZRT.RHPX.Core.User;
using ZRT.RHPX.Model.ReturnModel;

namespace ZRT.RHPX.UI.Controllers
{
    public class LoginController : GeneralController
    {
        //
        // GET: /Login/

        [HttpGet]
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
            return View();
        }


        [HttpPost]
        public ActionResult CheckUser(string UserName, string Password)
        {
            var result = new JsonReturnModel();
            if (UserName.Equals("admin") && Password.Equals("admin"))
            {
                //成功
                result.IsSuccess = true;

                UserEntity UserData = new UserEntity
                {
                    ID = Guid.NewGuid().ToString(),
                    UserName = UserName,
                    RealName = UserName
                };
                UserPrincipal CurrentUser = new UserPrincipal(UserData);

                //序列化用户对象
                var SerializeUserData = (new JavaScriptSerializer()).Serialize(UserData);
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddDays(1), false, SerializeUserData);
                string strCookieValue = FormsAuthentication.Encrypt(ticket);

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strCookieValue);
                cookie.HttpOnly = true;
                cookie.Secure = FormsAuthentication.RequireSSL;
                cookie.Domain = FormsAuthentication.CookieDomain;
                cookie.Path = FormsAuthentication.FormsCookiePath;

                //先删除cookie
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    HttpCookie oldCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                    oldCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(oldCookie);
                }
                //再添加cookie
                HttpContext.Response.Cookies.Add(cookie);
            }
            else
            {
                result.IsSuccess = false;
                result.Message = "登陆失败，用户名或密码错误!";
            }
            return Json(result);
        }
    }
}
